<html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>推流页面</title>
</head>

<body>
  <div>

  </div>
  <script>
    // datachannel对象
    let datachannel = null;

    // 订阅流用的Peerconnection
    let pc_sub = new RTCPeerConnection();

    let ws = new WebSocket('ws://127.0.0.1:9000');
    ws.addEventListener('open', () => {
      // 通知server pub已经上线
      ws.send(JSON.stringify({
        type: "subscribe"
      }))
    })

    ws.addEventListener('message', (event) => {
      let msg = JSON.parse(event.data);
      switch (msg.type) {
        case "start":
          break;

        case "offer":
          pc_sub.setRemoteDescription(msg).then(() => {
            pc_sub.createAnswer().then((answer) => {
              pc_sub.setLocalDescription(answer).then(() => {
                ws.send(JSON.stringify(answer));
              }).catch((err) => {

              })
            }).catch((err) => {
              console.error('create answer error', err);
            })
          }).catch((err) => {
            console.error('setRemoteDescription error', err);
          })
          break;

        default:
          pc_sub.addIceCandidate(msg);
          break;
      }
    })

    pc_sub.addEventListener('icecandidate', (event) => {
      if (event.candidate) {
        ws.send(JSON.stringify(event.candidate));
      }
    })

    pc_sub.addEventListener('datachannel', (event) => {
      console.log('recv datachannel', event.channel);
      datachannel = event.channel;
      datachannel.addEventListener('open', onDataChannelOpen);
      datachannel.addEventListener('close', onDataChannelClose);
      datachannel.addEventListener('error', onDataChannelError);
      datachannel.addEventListener('message', onDataChannelMessage);
    })

    function onDataChannelOpen() {
      console.log("sub datachannel open")
    }

    function onDataChannelClose() {
      console.log("sub datachannel close")
    }

    function onDataChannelError() {
      console.log("sub datachannel error")
    }

    function onDataChannelMessage(event) {
      console.log("sub datachannel messae:", event.data)
    }


  </script>
</body>

</html>